package com.github.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.bean.ServerUser;
import com.github.constant.MyConstant;
import com.github.manager.Manager;
import com.github.pojo.HttpResult;
import com.github.service.UserServer;
import com.github.util.SocketSendThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

import static com.github.constant.MyConstant.UserLoginAccount;

@RestController
public class ManagerController {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ServerProperties serverProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserServer userServer;
    @GetMapping("/api/manager/getManger")
    public ObjectNode getManger(String type) {
        ObjectNode jsonObject = objectMapper.createObjectNode();
        ObjectNode detailsNode = objectMapper.createObjectNode();
        Map<Object, Object> accountTokenMap = stringRedisTemplate.opsForHash().entries(MyConstant.UserLoginAccount);
        Map<Object, Object> tokenAccountMap = stringRedisTemplate.opsForHash().entries(MyConstant.UserLoginToken);

        // 根据不同type返回详细信息
        switch (type) {
            case "accountUserMap":
                // 返回所有ws账户的详细信息
                jsonObject.put("总数", Manager.accountUserMap.size());
                jsonObject.put("都在线数", Manager.accountUserMap.values().stream()
                        .filter(ServerUser::isAllOnline)
                        .count());
                jsonObject.put("server在线数", Manager.accountUserMap.values().stream()
                        .filter(ServerUser::isServerOnline)
                        .count());
                jsonObject.put("voice在线数", Manager.accountUserMap.values().stream()
                        .filter(ServerUser::isVoiceOnline)
                        .count());
                jsonObject.put("card在线数", Manager.accountUserMap.values().stream()
                        .filter(ServerUser::isCardOnline)
                        .count());
                for (Map.Entry<String, ServerUser> entry : Manager.accountUserMap.entrySet()) {
                    String key = entry.getKey();
                    ServerUser serverUser = entry.getValue();

                    ObjectNode userJson = objectMapper.createObjectNode();
                    userJson.put("account", serverUser.getAccount());
                    userJson.put("serverSession", serverUser.isServerOnline());
                    userJson.put("voiceSession", serverUser.isVoiceOnline());
                    userJson.put("cardSession", serverUser.isCardOnline());
                    detailsNode.set(key, userJson);
                }
                jsonObject.set("详情", detailsNode);
                break;
            case "sessionIDUserMap":
                // 返回所有ws连接的详细信息
                jsonObject.put("总数", Manager.sessionIDUserMap.size());
                for (Map.Entry<String, ServerUser> entry : Manager.sessionIDUserMap.entrySet()) {
                    String key = entry.getKey();
                    ServerUser serverUser = entry.getValue();

                    ObjectNode userJson = objectMapper.createObjectNode();
                    userJson.put("account", serverUser.getAccount());
                    userJson.put("serverSessionId", serverUser.getServerSessionId());
                    userJson.put("voiceSessionId", serverUser.getVoiceSessionId());
                    userJson.put("cardSessionId", serverUser.getCardSessionId());
                    detailsNode.set(key, userJson);
                }
                jsonObject.set("详情", detailsNode);
                break;
            case "sessionQueues":
                // 返回消息队列的详细信息
//                jsonObject.put("总数", SocketSendThread.sessionQueues.size());
//                for (Map.Entry<String, BlockingQueue<String>> entry : SocketSendThread.sessionQueues.entrySet()) {
//                    String key = entry.getKey();
//                    BlockingQueue<String> queue = entry.getValue();
//                    detailsNode.put(key, queue.size());
//                }
//                jsonObject.set("详情", detailsNode);
//                break;
            case "accountTokenMap":
                // 返回接口账户的详细信息
                jsonObject.put("总数", accountTokenMap.size());
                for (Map.Entry<Object, Object> entry : accountTokenMap.entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String)entry.getValue();
                    detailsNode.put(key, value);
                }
                jsonObject.set("详情", detailsNode);
                break;
            case "tokenAccountMap":
                // 返回TOKEN的详细信息
                jsonObject.put("总数", tokenAccountMap.size());
                for (Map.Entry<Object, Object> entry : tokenAccountMap.entrySet()) {
                    String key = (String) entry.getKey();
                    String value =(String) entry.getValue();
                    detailsNode.put(key, value);
                }
                jsonObject.set("详情", detailsNode);
                break;
//            case "loginTime":
//                // 返回登录时间的详细信息
//                jsonObject.put("总数", Manager.loginTime.size());
//                for (Map.Entry<String, Long> entry : Manager.loginTime.entrySet()) {
//                    String key = entry.getKey();
//                    Long value = entry.getValue();
//                    detailsNode.put(key, value);
//                }
//                jsonObject.set("详情", detailsNode);
//                break;
            default:
                // 处理未知类型
                jsonObject.put("ws账户数", Manager.accountUserMap.size());
                jsonObject.put("都在线数", Manager.accountUserMap.values().stream()
                        .filter(ServerUser::isAllOnline)
                        .count());
                jsonObject.put("ws连接数", Manager.sessionIDUserMap.size());
                jsonObject.put("ws消息队列数", SocketSendThread.sessionQueues.size());
                jsonObject.put("接口账户数", accountTokenMap.size());
                jsonObject.put("接口TOKEN数", tokenAccountMap.size());
//                jsonObject.put("接口登录时间数", Manager.loginTime.size());
                jsonObject.put("redis账户数", stringRedisTemplate.opsForHash().entries(MyConstant.UserInfoCache).size());
                jsonObject.put("数据库账户数", userServer.getAllUser().size());
                // 获取当前活跃线程数
                int activeThreads = Thread.activeCount();
                jsonObject.put("获取当前活跃线程数", activeThreads);

                // 获取所有线程的详细信息
                ThreadGroup group = Thread.currentThread().getThreadGroup();
                ThreadGroup topGroup = group;
                // 遍历获取最顶层的线程组
                while (group != null) {
                    topGroup = group;
                    group = group.getParent();
                }
                // 估算线程数量
                int estimatedSize = topGroup.activeCount() * 2;
                Thread[] threads = new Thread[estimatedSize];
                // 获取所有线程
                int actualSize = topGroup.enumerate(threads);
                jsonObject.put("获取所有线程", actualSize);

                // 获取配置的线程池参数
                int maxThreads = serverProperties.getTomcat().getThreads().getMax();
                int minSpareThreads = serverProperties.getTomcat().getThreads().getMinSpare();

                jsonObject.put("Tomcat最大线程数", maxThreads);
                jsonObject.put("Tomcat最小空闲线程数", minSpareThreads);
                break;
        }
        return objectMapper.createObjectNode().set("message", jsonObject);
    }
}
